package pt.eden.tomcat.jms;

import pt.eden.tomcat.jms.util.ResourceNamingUtil;

import javax.jms.ConnectionFactory;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;
import java.io.IOException;
import java.util.Hashtable;

/**
 * Custom resource factory to create JMS resources.
 *
 * @see <a href="http://tomcat.apache.org/tomcat-4.1-doc/jndi-resources-howto.html">Tomcat Spec.</a>
 */
public class JmsResourceFactory implements ObjectFactory {

    @Override
    public Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable<?, ?> environment) throws Exception {
        Reference ref = (Reference) obj;
        ResourceFactory factory = createReferenceFactory(ref.getClassName());
        return factory.createReference(ref);
    }

    private ResourceFactory createReferenceFactory(String className) throws IOException {
        if (className != null) {
            String resourceType = ResourceNamingUtil.getResourceName(className);
            if (resourceType != null) {
                return new GenericResourceFactoryImpl(resourceType);
            }
        }
        throw new IllegalArgumentException("The specified type '" + className + "' is not supported!");
    }
}

